<?php

error_reporting(0);
require_once dirname(dirname(__FILE__)) . '/include/backup.class.php';


$act = empty($_REQUEST["act"])?"":$_REQUEST["act"];

if($act == "checkmysql"){
	//校验mysql信息
	if(empty($_POST['host']) || empty($_POST['user']) || !isset($_POST['pwd']) || empty($_POST['port']) || empty($_POST['database'])){
		ajaxreturn('数据库信息不完整');
	}
	$pm = array(
		'host' => $_POST['host'],
		'uid' => $_POST['user'],
		'pwd' => $_POST['pwd'],
		'databases' => $_POST['database'],
		'port' => $_POST['port'],
	);
	try{
		$hp = new Sevstudio\MySQLHelper($pm);
		$hp->connect();
	}catch(Exception $e){
		ajaxreturn('数据库连接失败，请检查');
	}
	ajaxreturn("SUCCESS",true);
}else if($act == "install"){
	//开始安装
	if(empty($_POST['host']) || empty($_POST['user']) || empty($_POST['pwd']) || empty($_POST['port']) || empty($_POST['database'])){
		ajaxreturn('信息不完整');
	}
		
	$res = db_install($_POST['host'],$_POST['port'],$_POST['user'],$_POST['pwd'],$_POST['database']);
	if($res!== ""){
		ajaxreturn('系统安装失败，请重试');
	}else{

		$ini = array(
			"host"		=>$_POST['host'],
			"user"		=>$_POST['user'],
			"pwd"		=>$_POST['pwd'],
			"port"		=>$_POST['port'],
			"database"	=>$_POST['database'],
			"houtai"	=>'manage',
		);
		$fpath = dirname(dirname(__FILE__)).'/include/database.php';
		$text = "<?php\nreturn ".var_export($ini,true).';';
		file_put_contents($fpath,$text);
		file_put_contents("install_lock.txt", "install locked");
		ajaxreturn('houtai',true);
	}
}
function ajaxreturn($msg,$flag = false){
	header("Content-type:text/html;charset=utf-8");
	$data = array(
		"flag"	=> $flag?"1":"0",
		"msg"	=> $msg,
	);
	echo json_encode($data);
	exit();
}
function db_install($host,$port,$user,$pwd,$database){
	$filename = dirname(__FILE__).'/eptime.sql';
	if(!file_exists($filename)){
		return "数据库文件不存在";
	}
	$pm = array(
		'host' => $_POST['host'],
		'uid' => $_POST['user'],
		'pwd' => $_POST['pwd'],
		'databases' => $_POST['database'],
		'port' => $_POST['port'],
	);
	$success = false;
	try{
		$hp = new Sevstudio\MySQLHelper($pm);
		$success = $hp->Restore($filename);
	}catch(Exception $e){
		
	}
	if($success){
		return '';
	}
	return '数据库安装失败';
}

